package sdcncsi.ict.counter.web;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sdcncsi.ict.counter.CounterService;

public class HttpServletTool {
	//读取Cookie
	public static Cookie getCookie(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(name)) {
					return cookies[i];
				}
			}
		}
		return null;
	}

	//读取Cookie的值
	public static String getCookieValue(HttpServletRequest request, String name) {
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(name)) {
					return cookies[i].getValue();
				}
			}
		}
		return null;
	}
	
	//清空cookie
	public static void removeCookie(HttpServletResponse response, String name) {
		Cookie oldCookie = new Cookie(name, "");
		oldCookie.setMaxAge(0);//重点设置cookie过期时间为0秒   
		oldCookie.setPath("/");
		response.addCookie(oldCookie);
	}
	
	//添加cookie
	public static Cookie addCookie(HttpServletResponse response, String name, String value, int expiry) {
		Cookie newCookie = new Cookie(name, value);
		newCookie.setMaxAge(expiry);
		newCookie.setPath("/");
		response.addCookie(newCookie);
		return newCookie;
	}
	
	//整理HttpServletRequest参数到HashMap
	public static Map<String, String> getRequestMap(HttpServletRequest request) {
		Map<String, String> requestMap = new HashMap<String, String>();
		//"Parameters:"
		Enumeration<?> params = request.getParameterNames();
		while(params.hasMoreElements()){
			String param = params.nextElement().toString();
			String value = request.getParameter(param);
			//System.out.println("["+param+"]: "+request.getParameter(param));
			requestMap.put(param.toLowerCase(), value);
		}
		//"Headers:"
		Enumeration<?> headers = request.getHeaderNames();
		while(headers.hasMoreElements()){
			String header = headers.nextElement().toString();
			String value = request.getHeader(header);
			//System.out.println("["+header+"]: "+request.getHeader(header));
			requestMap.put(header.toLowerCase(), value);
		}
		//ip
		//System.out.println("Locale:"+request.getLocale().getLanguage()+";"+request.getLocale().getCountry());
		//System.out.println("Local:"+request.getLocalName()+"="+request.getLocalAddr()+":"+request.getLocalPort());
		//System.out.println("Remote:"+request.getRemoteHost()+"="+request.getRemoteAddr()+":"+request.getRemotePort());
		requestMap.put("ip", request.getRemoteAddr());
		//session
		requestMap.put("session",request.getSession().getId());
		requestMap.put("req_seesion", request.getRequestedSessionId());
		//cookie
		String value = getCookieValue(request, CounterService.COOKIE_NAME);
		requestMap.put(CounterService.COOKIE_NAME, value);
		return requestMap;
	}
}
